package com.example.distributed_lock.lock;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.util.Collections;
import java.util.UUID;

/**
 * 可重入锁
 * @author :ld
 * @date :2021/7/9
 */
public class ReentrantRedisLock implements RedisLock{
    /**
     * 设置锁对应的key
     */
    private final String key;
    /**
     * redis模板
     */
    private final StringRedisTemplate redisTemplate;

    /**
     * 线程信息的前缀
     */
    private final String ID_PREFIX = UUID.randomUUID().toString();

    /**
     * 锁释放时间
     */
    private String releaseTime;

    /**
     *
     */
    private static final DefaultRedisScript<Long> LOCK_SCRIPT;
    /**
     * 释放锁的lua脚本对象
     */
    private static final DefaultRedisScript<Object> UNLOCK_SCRIPT;

    static {
        //加载获取锁lua
        LOCK_SCRIPT = new DefaultRedisScript<>();
        LOCK_SCRIPT.setScriptSource(new ResourceScriptSource(new ClassPathResource("static/reentrant_lock.lua")));

        //加载释放锁lua
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setScriptSource(new ResourceScriptSource(new ClassPathResource("static/reentrant_unlock.lua")));
    }

    public ReentrantRedisLock(String key, StringRedisTemplate redisTemplate) {
        this.key = key;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean tryLock(long releaseTime) {
        //记录释放时间
        this.releaseTime = String.valueOf(releaseTime);
        //执行脚本
        Long res = redisTemplate.execute(LOCK_SCRIPT, Collections.singletonList(key), ID_PREFIX + Thread.currentThread().getId(), this.releaseTime);
        return res != null && res.intValue()==1;
    }

    @Override
    public void unlock() {
        //执行脚本
        redisTemplate.execute(UNLOCK_SCRIPT,Collections.singletonList(key),ID_PREFIX+Thread.currentThread().getId(),this.releaseTime);
    }
}
